package pers.cnzdy.tutorial.Chapter5_UI.Section8_Fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import pers.cnzdy.tutorial.Chapter5_UI.Section7_ListView.KnowledgePoints;
import pers.cnzdy.tutorial.R;

public class KPointsFragment extends Fragment implements AdapterView.OnItemClickListener {
    public static String TAG = "KPointsFragment";

    ListView        kpointsListView;
    KnowledgePoints kpoints;
    KPointsAdapter  adapter;
    boolean         isPAD;  // 平板电脑

    public KPointsFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_kpoints, container, false);
        kpointsListView = view.findViewById(R.id.kpoints_caption_list_view);
        kpointsListView.setAdapter(adapter);
        kpointsListView.setOnItemClickListener(this);
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        kpoints = new KnowledgePoints();
        adapter = new KPointsAdapter(context, R.layout.kpoint_item,
                kpoints.getKnowledgePointList());
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        isPAD = getActivity().findViewById(R.id.kpoint_detail_frag) != null;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        KnowledgePoints.KnowledgePoint kpoint = kpoints.getKnowledgePointList().get(position);

        Log.d(TAG, "是否是平板电脑: " + isPAD);
        if (isPAD) {
            KPointDetailFragment detailFragment =
                    (KPointDetailFragment)getFragmentManager()
                            .findFragmentById(R.id.kpoint_detail_pad_frag);
            detailFragment.refresh(kpoint.getCaption(), kpoint.getDetail());
        } else {
            KPointDetailActivity.startUp(getActivity(), kpoint.getCaption(), kpoint.getDetail());
        }
    }
}
